<template>
  <div class="home" v-if="init">
    <y-menu :is-collapse="isCollapse" v-if="showMenu"></y-menu>
    <el-container>
      <el-header class="home-header">
        <el-link class="collapse-link" :underline="false" @click="isCollapse = !isCollapse">
          <i :class="isCollapse ? 'el-icon-s-unfold' : 'el-icon-s-fold'"></i>
        </el-link>
        <div class="home-user">
          <el-link :underline="false" @click="toSelf">{{userInfo.name}}</el-link>
          <y-notification></y-notification>
          <el-link class="fa fa-sign-in" :underline="false" @click="logout"></el-link>
        </div>
      </el-header>
      <el-main class="home-main">
        <y-tabs></y-tabs>
        <div class="home-content">
          <keep-alive ref="keepAlive" :include="cachePage">
            <router-view ref="routerView" v-if="showView"/>
          </keep-alive>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script>

import YMenu from '@/components/Menu/Menu.vue'
import YTabs from '@/components/Tabs/Tabs'
import YNotification from "@/components/Notification/YNotification";
import utils from '@/lib/utils'
import getEnum from '@/lib/enum'
import { Loading } from 'element-ui';
export default {
  name: 'Home',
  components: {
    YMenu, YTabs, YNotification
  },
  provide(){
    return{
      addCache: this.addCache,
      delCache: this.delCache,
      logout: this.logout,
      getDict: this.getDict,
      getDictName: this.getDictName,
      getDictNameSync: this.getDictNameSync,
      addEventOnResize: this.addEventOnResize,
      registerCustomEvent: this.registerCustomEvent,
      '__GLOBAL': {
        TITLE: '会议室管理系统'
      },
      getEnum,
      ...utils
    }
  },
  created(){
    if(this.$route.name === 'Home'){
      this.loading = Loading.service({
        lock: true,
        text: '重定向中，请稍后...',
        background: 'rgba(0, 0, 0, 0.2)'
      })
    }
    //TODO
    let user = localStorage.getItem('user');
    if(!user){
      this.$router.replace({
        name: 'Login'
      })
      return;
    }
    this.init = true;
    this.userInfo = JSON.parse(user);
    //注册刷新事件
    this.$bus.$on("reload", (function(name){
      this.$nextTick(() => {
        let $view = this.$refs['routerView'];
        if($view){
          let cache = $view.$vnode.parent.componentInstance.cache;
          Object.entries(cache).map(([key, value]) => {
            if(value && value.name === name){
              delete cache[key];
            }
          })
          this.showView = false;
          this.$nextTick(() => {
            this.showView = true
          });
        }
      })
    }).bind(this));
    //TODO 字典刷新事件
    /*this.$bus.$on('refreshDict', key => {
      if(this.dict[key]){
        this.$set(this.dict, key, false);
      }
    });*/
    //重定向事件，跳转至menu的第一个菜单
    this.$bus.$on("redirect", (function(menu){
      this.loading && this.loading.close && this.loading.close();
      if(menu && this.$route.name === 'Home'){
        this.$router.push({
          path: menu.menuRouter
        })
      }
    }).bind(this));
    this.showMenu = true
  },
  data(){
    return {
      init: false,
      isCollapse: false,
      userInfo: {},
      showView: true,
      showMenu: false,
      cachePage: [],
      dict: {},//这里维护一份字典的缓存，
      eventMap: {},//监听事件的缓存
      loading: ''
    }
  },
  beforeRouteLeave(to, from, next) {
    this.loading && this.loading.close && this.loading.close();
    next();
  },
  methods:{
    toSelf(){//跳转我的信息
      this.$router.push({
        name: 'selfCenter'
      });
    },
    logout(){
      this.$yAxios({
        url: this.$api.login.logout
      });
      this.$nextTick(() => {
        localStorage.removeItem('user');
        localStorage.removeItem('Authorization');
        this.$router.replace({
          name: 'Login'
        })
      })
    },
    addCache({name}){
      if(!this.cachePage.includes(name)){
        this.cachePage.push(name);
      }
    },
    delCache({name}){
      let index = this.cachePage.indexOf(name);
      index >=0 && this.cachePage.splice(index, 1);
    },
    /*以下都是interface*/
    async getDict(code){
      return new Promise(resolve => {
        if(this.dict[code]) resolve(this.dict[code]);
        else{
          this.$yAxios({
            url: this.$api.system.queryDict,
            data:{
              pcode: code
            }
          }, info => {
            this.$set(this.dict, code, info);
            resolve(this.dict[code])
          }, e => {
            resolve([])
          });
        }
      });
    },
    getDictName(code, dict){
      return new Promise(async resolve => {
        let options = await this.getDict(dict);
        resolve(this.$$getArrayName(code, options));
      })
    },
    getDictSync(code){
      if(this.dict[code] && this.dict[code] !== true) return this.dict[code];
      else{
        if(this.dict[code] === true){
          return [];
        }else{
          this.$set(this.dict, code, true);
          this.$yAxios({
            url: this.$api.system.queryDict,
            data:{
              pcode: code
            }
          }, info => {
            this.$set(this.dict, code, info);
          },e => {
            this.$delete(this.dict, code);
          });
          return []
        }
      }
    },
    getDictNameSync(code, dict){
      let options = this.getDictSync(dict);
      return options.length ? this.$$getArrayName(code, options) : [];
    },
    //注册resize事件
    addEventOnResize(fn){
      let originFn = window.onresize;
      window.onresize = () => {
        originFn && originFn();
        fn();
      }
    },
    //自定义事件
    registerCustomEvent(event, key, callback, isOnce = false){
      if(!this.eventMap[event]){
        this.eventMap[event] = {};
        this.$bus.$on(event, (args) => {
          Object.keys(this.eventMap[event]).map(key => {
            let {callback, isOnce} = this.eventMap[event][key];
            callback(args);
            isOnce && delete this.eventMap[event][key]
          })
        })
      }
      this.eventMap[event][key] = {
        callback, isOnce
      };
    }
  }
}
</script>

<style lang="less" scoped>
.home{
  width: 100%;
  height: 100%;
  display: flex;
  >.menu{
    flex-shrink: 0;
    /*&.el-menu--collapse{
      min-width: 64px;
    }*/
  }
  >.el-container{
    flex-grow: 2;
  }
  .home-header{
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 61px!important;
    border-bottom: 1px solid #e6e6e6;
    background-color: @common-color;
    padding-left: 0;
    .el-link{
      color: #fff!important;
    }
    >.collapse-link{
      font-size: 36px;
    }
    >.home-user{
      >*{
        margin: 0 10px;
        font-size: 18px;
      }
      >.fa{
        font-size: 24px;
      }
    }
  }
  .home-main{
    height: 100%;
    position: relative;
    display: block;
    padding: 0;
    overflow: hidden;
    >.home-content{
      height: calc(100% - 51px);
      padding: 20px;
      overflow: auto;
    }
  }
}
</style>
